package cn.edu.zafu.bigdata.x.zhaobolei.Eighth;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class TCP_Client {
    public static void main(String[] args) {
        String host = "127.0.0.1";      //回环地址,特殊的ip
        int port = 123;
        try (Socket socket = new Socket(host, port);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             Scanner scanner = new Scanner(System.in)) {

            System.out.println("已连接到服务器：" + host + ":" + port);

            Thread listener = new Thread(() -> {
                try {
                    String serverMessage;
                    while ((serverMessage = in.readLine()) != null) {
                        System.out.println("服务器回复: " + serverMessage);
                    }
                } catch (IOException e) {
                    System.out.println("从服务器读取消息时出错: " + e.getMessage());
                }
            });
            listener.start();

            while (true) {
                System.out.print("输入消息发送到服务器: ");
                String message = scanner.nextLine();
                out.println(message);
                if ("exit".equalsIgnoreCase(message)) {
                    break;
                }
            }
        } catch (IOException e) {
            System.out.println("客户端连接失败: " + e.getMessage());
        }
    }
}